package com.piece.mall.listener;

import com.piece.core.framework.support.dto.PayloadDTO;
import com.piece.core.framework.util.message.MessageFactory;
import com.piece.core.framework.util.string.JsonUtil;
import com.piece.core.mongo.entity.MongoMessageLog;
import com.piece.core.pay.client.PayClient;
import com.piece.core.pay.client.PayClientFactory;
import com.piece.core.pay.dto.PayOrderNotifyRespDTO;
import com.piece.mall.api.constant.MallRegisterConstants;
import com.piece.mall.model.OmsOrder;
import com.piece.mall.service.PaymentService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * 支付超时自动关闭订单
 */
@Slf4j
@Component
@RabbitListener(queues = MallRegisterConstants.ORDER_DLX_QUEUE_NAME, containerFactory = "singleListenerContainer")
public class OrderAutoCloseListener {

    @Resource
    private MessageFactory messageFactory;

    @Resource
    private PayClientFactory payClientFactory;

    @Resource
    private PaymentService paymentService;

    @RabbitHandler
    public void handleOrderRelease(PayloadDTO payload, Message message, Channel channel) throws Exception {
        try {
            MongoMessageLog messageLog = JsonUtil.toBean(payload.getEntity(), MongoMessageLog.class);
            messageLog.setTitle("订单超时未支付");
            messageLog.setMethod("omsOrderService.closeOrder");
            // 查询支付渠道是否支付成功
            OmsOrder order = JsonUtil.toBean(messageLog.getEntity(), OmsOrder.class);
            PayClient payClient = payClientFactory.getPayClient(order.getPayType(), order.getChannelCode());
            PayOrderNotifyRespDTO payResult = payClient.tradeUnifiedQuery(order.getOrderSn());
            payResult.setOrderExtensionNo(order.getOrderSn());
            if ("TRADE_SUCCESS".equals(payResult.getTradeStatus())) {
                messageLog.setTitle("订单支付成功");
                messageLog.setMethod(null);
                paymentService.paySuccess(payResult, order.getPayType(), order.getChannelCode());
            } else {
                messageLog.setDesc(payResult.getData());
            }
            payload.setEntity(JsonUtil.toJson(messageLog));
            messageFactory.getOperator(payload.getOperator()).doReceive(payload);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception e) {
            // 解锁失败,删除消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            // 消息重新放回队列
            messageFactory.get().reSend(payload);
        }
    }
}
